package com.stylefeng.guns.modular.small.controller;

import com.stylefeng.guns.config.zimg.OSSClient;
import com.stylefeng.guns.config.zimg.ZimgClient;
import com.stylefeng.guns.modular.small.model.BizConsumer;
import com.stylefeng.guns.modular.small.service.IBizConsumerService;
import com.stylefeng.guns.modular.small.util.ImageUtil;
import com.stylefeng.guns.modular.small.util.ResponseCode;
import com.stylefeng.guns.modular.small.util.ResponseResultDTO;
import com.stylefeng.guns.modular.system.model.ArtificerMeans;
import com.stylefeng.guns.modular.system.service.IArtificerMeansService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.List;

/**
 * @apiDefine Upload
 * @apiError UploadNotFound The id of the Upload was not found.
 * @apiErrorExample Error-Response:
 * HTTP/1.1 404 Not Found
 * {
 * "error": "UploadNotFound"
 * }
 */
@Controller
@Slf4j
@RequestMapping("/upload")
public class UploadPictController {

    @Resource
    private ZimgClient zimgClient;

    @Autowired
    private IArtificerMeansService artificerMeansService;

    @Resource
    private OSSClient ossClientUtil;

    @Resource
    private IBizConsumerService iBizConsumerService;

    /**
     * @api {POST} /upload/picture  上传图片增加水印
     * @apiName uploadFile
     * @apiGroup Upload
     *
     * @apiParam {Object} file MultipartFile类型的图片，名为file 仅支持"jpeg", "jpg", "png", "gif", "webp".
     * @apiParam {Number} id 登录用户的id.
     * @apiParam {String} userType 登录用户的类型  1为技师 .
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     * "data": "75a71642bd246f994a243dc92770e580",
     * "msg": "SUCCESS",
     * "status": "0000",
     * "userType": ""
     * }
     */
    @RequestMapping("/picture")
    @ResponseBody
    public ResponseResultDTO uploadImage(HttpServletRequest request, String userType, Integer id) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("file");
        MultipartFile file = files.get(0);
        ResponseResultDTO responseResultDTO = new ResponseResultDTO();
        if (file == null || StringUtils.isBlank(userType) || id==null) {
            responseResultDTO.setMsg("PARAM-NULL");
            responseResultDTO.setStatus("-1");
            return responseResultDTO;
        }
        try {
            //增加水印
//            file = zimgClient.addWorkMarkToMutipartFile(file, "测试水印");
            String[] names = file.getOriginalFilename().split("\\.");
            if(!"jpeg,jpg,png,gif,webp".contains(names[names.length-1])){
                responseResultDTO.setMsg("请上传图片格式!");
                responseResultDTO.setStatus("-1");
                return responseResultDTO;
            }
            String imageId = zimgClient.uploadImg(file.getBytes(), names[names.length-1]);
            if("1".equals(userType)){
                ArtificerMeans  artificerMeans = artificerMeansService.selectById(id);
                if(artificerMeans==null){
                    responseResultDTO.setMsg("该技师不存在!");
                    responseResultDTO.setStatus("-1");
                    return responseResultDTO;
                }
                BufferedImage bufferedImage=zimgClient.cut(file);
                //此处把图片压成400×500的缩略图
//                bufferedImage=Thumbnails.of(bufferedImage).scale(0.3f).outputQuality(0.09f).asBufferedImage();//变为400*300,遵循原图比例缩或放到400*某个高度
                byte[] bytes = ImageUtil.encodeImgageToByte(bufferedImage);
                String base64= zimgClient.uploadImg(bytes, names[names.length-1]);
                artificerMeans.setImgUrl(imageId);
                artificerMeans.setBase64(base64);
                artificerMeans.setUpdateTime(new Date());
                artificerMeansService.updateById(artificerMeans);
                log.info("将图片转为base64为：{}", base64);
            }
            responseResultDTO.setData(imageId);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("系统异常，异常信息：{}", e.getMessage());
            responseResultDTO.setMsg(ResponseCode.ERROR.getDesc());
            responseResultDTO.setStatus(ResponseCode.ERROR.getCode());
        }
        return responseResultDTO;
    }

    /**
     * @api {POST} /upload/uploadBase  上传图片
     * @apiName uploadBase64Image
     * @apiGroup Upload
     *
     * @apiParam {Object} file MultipartFile类型的图片，名为file.
     *
     * @apiSuccess  {String}  data  图片MD5
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     * "data": "75a71642bd246f994a243dc92770e580",
     * "msg": "SUCCESS",
     * "status": "0000",
     * "userType": ""
     * }
     */
    @RequestMapping("/uploadBase")
    @ResponseBody
    public ResponseResultDTO uploadBase64Image(HttpServletRequest request) {
        ResponseResultDTO responseResultDTO = new ResponseResultDTO();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("file");
        MultipartFile file = files.get(0);
        if (file == null) {
            responseResultDTO.setMsg("PARAM-NULL");
            responseResultDTO.setStatus("-1");
            return responseResultDTO;
        }
        try {
            String[] names = file.getOriginalFilename().split("\\.");
            String imageId = zimgClient.uploadImg(file.getBytes(), names[names.length-1]);
            log.info("将图片MD5为：{}", imageId);
            responseResultDTO.setData(imageId);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("系统异常，异常信息：{}", e.getMessage());
            responseResultDTO.setMsg(ResponseCode.ERROR.getDesc());
            responseResultDTO.setStatus(ResponseCode.ERROR.getCode());
        }
        return responseResultDTO;
    }

    @RequestMapping("/oss/image")
    @ResponseBody
    public ResponseResultDTO ossUploadImage(HttpServletRequest request, String userType, Integer id) {
        ResponseResultDTO responseResultDTO = new ResponseResultDTO();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("file");
        MultipartFile file = files.get(0);
        if (file == null || StringUtils.isBlank(userType) || id==null) {
            responseResultDTO.setMsg("PARAM-NULL");
            responseResultDTO.setStatus("-1");
            return responseResultDTO;
        }
        String[] names = file.getOriginalFilename().split("\\.");
        if(!"jpeg,jpg,png,gif,webp".contains(names[names.length-1])){
            responseResultDTO.setMsg("请上传图片格式!");
            responseResultDTO.setStatus("-1");
            return responseResultDTO;
        }
        try {
            String  imgMd5= ossClientUtil.uploadImg(file,"uploadima","images/small/",file.getOriginalFilename());
            if("1".equals(userType)){
                ArtificerMeans  artificerMeans = artificerMeansService.selectById(id);
                if(artificerMeans==null){
                    responseResultDTO.setMsg("该技师不存在!");
                    responseResultDTO.setStatus("-1");
                    return responseResultDTO;
                }
                artificerMeans.setImgUrl(imgMd5);
                artificerMeans.setUpdateTime(new Date());
                artificerMeansService.updateById(artificerMeans);
            }else{
                BizConsumer bizConsumer=iBizConsumerService.selectById(id);
                if(bizConsumer==null){
                    responseResultDTO.setMsg("该用户不存在!");
                    responseResultDTO.setStatus("-1");
                    return responseResultDTO;
                }
                bizConsumer.setConsumerPict(imgMd5);
                bizConsumer.setUpdateDate(new Date());
                iBizConsumerService.updateById(bizConsumer);
            }
            responseResultDTO.setData(imgMd5);
            log.info("上传图片为：{}", imgMd5);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("系统异常，异常信息：{}", e.getMessage());
            responseResultDTO.setMsg(ResponseCode.ERROR.getDesc());
            responseResultDTO.setStatus(ResponseCode.ERROR.getCode());
        }
        return responseResultDTO;
    }


    @RequestMapping("/oss/uploadImageA")
    @ResponseBody
    public ResponseResultDTO ossUploadImageA(HttpServletRequest request) {
        ResponseResultDTO responseResultDTO = new ResponseResultDTO();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("file");
        MultipartFile file = files.get(0);
        if (file == null) {
            responseResultDTO.setMsg("PARAM-NULL");
            responseResultDTO.setStatus("-1");
            return responseResultDTO;
        }
        String[] names = file.getOriginalFilename().split("\\.");
        if(!"jpeg,jpg,png,gif,webp".contains(names[names.length-1])){
            responseResultDTO.setMsg("请上传图片格式!");
            responseResultDTO.setStatus("-1");
            return responseResultDTO;
        }
        try {
            String  imgMd5= ossClientUtil.uploadImg(file,"uploadima","images/small/",file.getOriginalFilename());
            responseResultDTO.setData(imgMd5);
            log.info("上传图片为：{}", imgMd5);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("系统异常，异常信息：{}", e.getMessage());
            responseResultDTO.setMsg(ResponseCode.ERROR.getDesc());
            responseResultDTO.setStatus(ResponseCode.ERROR.getCode());
        }
        return responseResultDTO;
    }
}
